package com.android.ailaoshan.picture;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.io.File;
import java.util.ArrayList;

/**
 * 显示，编辑图片信息
 */
public class PictureActivity extends AppCompatActivity implements OnItemClickListener {

    private Context mContext;

    private Toolbar toolbar;

    private final String PIC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Picture" + File.separator;

    /**
     * 是否保护
     */
    private int protect = 2;

    private PictureAdapter adapter;
    private ArrayList<String> pathList;

    /**
     * 保存类型
     */
    private int saveType = 1;
    private String rDescribe = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture_activity);

        mContext = PictureActivity.this;
        toolbar = findViewById(R.id.collection_picture_voice_toolbar);

        // 获取List
        pathList = getIntent().getStringArrayListExtra("picName");
        saveType = getIntent().getIntExtra("saveType",1);
        rDescribe = getIntent().getStringExtra("describe");

        SwipeRecyclerView recyclerView = findViewById(R.id.collection_picture_voice_recycler);

        // 点击事件
        recyclerView.setOnItemClickListener(this);

        // 设置布局方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        // 适配器
        adapter = new PictureAdapter(mContext);
        adapter.notifyDataSetChanged(pathList);
        recyclerView.setAdapter(adapter);

        // 尾布局，添加图片
        if(saveType != 3){
            View footView = getLayoutInflater().inflate(R.layout.item_add,recyclerView,false);
            footView.findViewById(R.id.collection_add_picture).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent,203);
                }
            );
            recyclerView.addFooterView(footView);
        }
    }

    @Override
    protected void onStart(){
        super.onStart();

        toolbar.setNavigationOnClickListener(
            (v) -> {
                if(saveType != 3){
                    showExitMessage();
                }else{
                    finish();
                }
            }
        );

        EditText inputBox = findViewById(R.id.collection_text_input);
        inputBox.setText(rDescribe);

        Button saveBtn = findViewById(R.id.collection_picture_voice_save);
        if(saveType == 3){
            saveBtn.setVisibility(View.INVISIBLE);
        }
        saveBtn.setOnClickListener(
             (v) -> {
                 if(pathList.size() > 0){
                     // 获取输入的描述信息
                     String inputStr = inputBox.getText().toString().trim();

                     UpdatePicture updatePicture = new UpdatePicture();
                     updatePicture.savePictureInfo(pathList,protect,inputStr,saveType);
                 }else{
                     Toast.makeText(mContext,"没有可保存的信息",Toast.LENGTH_SHORT).show();
                 }
                 finish();
             }
        );

        Switch isProtect = findViewById(R.id.collection_picture_voice_switcher);
        isProtect.setOnCheckedChangeListener(
            (CompoundButton switcherBtn,boolean isSwitcher) -> {
                if(protect == 2){
                    protect = 1;
                }else{
                    protect = 2;
                }
            }
        );
    }


    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);

        switch (requestCode){
            // 添加图片
            case 203:{
                if(resultCode == RESULT_OK){
                    MyHandler myHandler = new MyHandler();
                    DealPicture dealPicture = new DealPicture();
                    dealPicture.copyImageFile(data,mContext,myHandler);
                }
                break;
            }
            // 删除图片
            case 210:{
                if(resultCode == 603){
                    String deleteName = data.getStringExtra("fileName");
                    if( !deleteName.equals("") ){
                        pathList.remove(deleteName);
                        if(adapter != null){
                            adapter.notifyDataSetChanged(pathList);
                        }
                    }
                }
                break;
            }
            default: break;
        }
    }

    /**
     * 添加图片后回调
     */
    public class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 204:{
                    String addFileName = msg.obj.toString();
                    // 文件名存在
                    if( !addFileName.equals("") ){
                        // 文件名数组存在
                        if(pathList != null){
                            pathList.add(addFileName);
                            // 适配器存在
                            if(adapter != null){
                                adapter.notifyDataSetChanged(pathList);
                            }
                        }
                    }
                    break;
                }
                default: break;
            }
        }
    }

    /**
     * 图片点击事件
     */
    @Override
    public void onItemClick(View itemView, int position) {
        String xPath = PIC_PATH + pathList.get(position);
        File pictureFile = new File(xPath);
        if(pictureFile.exists()){
            Intent intent = new Intent(PictureActivity.this,PlayActivity.class);
            intent.putExtra("fileName",pictureFile.getName());
            intent.putExtra("saveType",saveType);
            startActivityForResult(intent,210);
        }else{
            Toast.makeText(mContext,"图片文件不存在",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 点击了返回
     */
    @Override
    public void onBackPressed(){
        if(saveType != 3){
            showExitMessage();
        }else{
            finish();
        }
    }


    /**
     * 提示框
     */
    private void showExitMessage(){
        new QMUIDialog.MessageDialogBuilder(mContext)
                .setTitle("退出")
                .setMessage("现在退出这些记录将不能保存，确定退出吗？")
                .addAction("取消",new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction(0,"退出",QMUIDialogAction.ACTION_PROP_NEGATIVE,new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if(pathList != null){
                            UpdatePicture updatePicture = new UpdatePicture();
                            updatePicture.deleteAllPicture(pathList);

                            // 退出当前活动
                            finish();
                        }
                        dialog.dismiss();
                    }
        }).create(R.style.QMUI_Dialog).show();
    }
}
